<template>
  <div class="addTemplate_container">
    <el-form
      ref="TemplateRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      style="height: 760px; overflow: auto"
    >
      <el-card class="box-card" shadow="always" style="background: #fafafa">
        <template #header>
          <div class="card-header" style="padding-bottom: 4px">
            <span>基本信息</span>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称:" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="(item, index) in contract_status"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板说明:" prop="illustration">
              <el-input
                v-model="form.illustration"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
                show-word-limit
                maxlength="500"
                placeholder="请输入模板说明"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card
        class="box-card"
        shadow="always"
        style="background: #fafafa; margin-top: 15px"
      >
        <template #header>
          <div
            class="card-header"
            style="
              padding-bottom: 4px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <span>评估标准</span>
            <el-button type="primary" size="small" plain @click="addTableData">新增</el-button>
          </div>
        </template>
        <div>
          <el-table
            v-loading="loading"
            :data="form.evaluationCriteriaList"
            stripe
            border
            max-height="250"
          >
            <el-table-column label="分值" align="center" width="350">
              <template #default="scope">
                <el-input
                  v-model.number="scope.row.beginScore"
                  style="width: 150px"
                />~
                <el-input
                  v-model.number="scope.row.endScore"
                  style="width: 150px"
                />
              </template>
            </el-table-column>
            <el-table-column label="评估结果" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.evaluationResult" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.row, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <el-card
        class="box-card"
        shadow="always"
        style="background: #fafafa; margin-top: 15px"
      >
        <template #header>
          <div
            class="card-header"
            style="
              padding-bottom: 4px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <span>评估项目</span>
            <el-button type="primary" size="small" plain @click="add"
              >新增</el-button
            >
          </div>
        </template>
        <div>
          <el-card
            class="box-card"
            style="background: #ffffff; margin-top: 15px"
            shadow="never"
            v-for="(item, index) in form.evaluationItemList"
            :key="index"
          >
            <template #header>
              <div
                class="card-header"
                style="
                  padding-bottom: 4px;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                "
              >
                <span>{{ item.name }}</span>
                <div>
                  <el-button
                    type="success"
                    size="small"
                    plain
                    icon="Edit"
                    @click="editEvaluationItem(item, index)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    plain
                    icon="Delete"
                    @click="evaluationItemDel(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </template>
            <div>
              <el-table :data="item.evaluationItemOptionList" stripe border>
                <el-table-column label="选项" prop="name" />
                <el-table-column label="分值" prop="score" width="150" />
              </el-table>
            </div>
          </el-card>
        </div>
      </el-card>
      <el-card
        class="box-card"
        shadow="always"
        style="background: #fafafa; margin-top: 15px"
      >
        <div style="text-align: right; padding-right: 50px">

          <el-button
            type="primary"
            style="margin-left: 20px"
            @click="submitFormevaluationDebounceHandler"
            >确 定</el-button
          >
          <el-button @click="goCancel">取 消</el-button>
        </div>
      </el-card>
    </el-form>

    <el-dialog
      v-model="open"
      :title="title"
      append-to-body
      width="800px"
      v-if="open"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="addevaluationItemRef"
          :model="addevaluationItem"
          :rules="evaluationRules"
          label-width="90px"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input
              v-model="addevaluationItem.name"
              placeholder="请输入项目名称"
              style="width: 600px"
            />
            <el-button
              type="primary"
              size="small"
              plain
              @click="addProject"
              style="margin-left: 20px"
              >新增</el-button
            >
          </el-form-item>
          <div>
            <el-table
              :data="addevaluationItem.evaluationItemOptionList"
              stripe
              border
              max-height="250"
            >
              <el-table-column label="选项">
                <template #default="scope">
                  <el-input v-model="scope.row.name" />
                </template>
              </el-table-column>
              <el-table-column label="分值" align="center" width="150">
                <template #default="scope">
                  <el-input v-model.number="scope.row.score" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template #default="scope">
                  <el-button
                    link
                    type="danger"
                    icon="Delete"
                    @click="handleProject(scope.row, scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="addTemplate">
  import {
    evaluationTemplateInfo,
    evaluationTemplateSave,
    evaluationTemplateUpdate,
    serviceItemUpdata,
  } from "@/api/homeBed";

  const { proxy } = getCurrentInstance();
  const { sys_normal_disable, contract_status } = proxy.useDict(
    "sys_normal_disable",
    "contract_status",
  );
  const route = useRoute();
  const router = useRouter();
  const loading = ref(false);
  const editIndex = ref(0);
  const open = ref(false);
  const addEditFlag = ref("add");
  const title = ref("新增评估项目");
  import { debounce } from "@/utils/debounce.js";

  const data = reactive({
    form: {
      evaluationCriteriaList: [
        {
          beginScore: null,
          endScore: null,
          evaluationResult: null,
        },
      ],
      status: "1",
      evaluationItemList: [],
    },
    rules: {
      name: [
        { required: true, message: "请输入模板名称", trigger: "blur" },
        { required: true, min: 1, max: 50, message: "模板名称不超过50个字符", trigger: "blur" }
      ],
      illustration: [
        { required: false, message: "请输入模板说明", trigger: "blur" },
        { required: false, min: 1, max: 500, message: "模板说明不超过500个字符", trigger: "blur" }
      ]
    },
    evaluationRules: {
      name: [{ required: true, message: "请输入评估项目名称", trigger: "blur" }],
    },
    addevaluationItem: {
      name: "",
      evaluationItemOptionList: [
        {
          name: null,
          score: null,
        },
        {
          name: null,
          score: null,
        }
      ],
    },
  });

  const { form, rules, addevaluationItem, evaluationRules } = toRefs(data);

  function addTableData() {
    form.value.evaluationCriteriaList.push({
      leftPoint: null,
      rightPoint: null,
      notes: null,
    });
  }

  function evaluationItemDel(index) {
    proxy.$modal
      .confirm("是否确认删除该数据项？")
      .then(function () {
        form.value.evaluationItemList.splice(index, 1);
        proxy.$modal.msgSuccess("删除成功");
      })

      .catch(() => {});
  }

  function editEvaluationItem(data, index) {
    addevaluationItem.value = data;
    addEditFlag.value = "edit";
    editIndex.value = index;
    open.value = true;
  }

  function handleDelete(data, index) {
    console.log("data", data, index);
    if (form.value.evaluationCriteriaList.length <= 1) {
      proxy.$modal.msgError("评估标准不能低于1个");
      return false;
    }
    form.value.evaluationCriteriaList.splice(index, 1);
  }

  function handleProject(data, index) {
    if (addevaluationItem.value.evaluationItemOptionList.length <= 3) {
      proxy.$modal.msgError("评估项目选项不能低于3个");
      return false;
    } else {
      addevaluationItem.value.evaluationItemOptionList.splice(index, 1);
    }
  }

  function goCancel() {
    router.go(-1);
  }

  function add() {
    addEditFlag.value = "add";
    open.value = true;
  }

  function addProject() {
    addevaluationItem.value.evaluationItemOptionList.push({
      name: null,
      score: null,
    });
  }

  function cancel() {
    addevaluationItem.value = {
      name: "",
      evaluationItemOptionList: [
        {
          name: null,
          score: null,
        },
        {
          name: null,
          score: null,
        },
        {
          name: null,
          score: null,
        },
      ],
    };
    proxy.resetForm("addevaluationItemRef");
    open.value = false;
  }
  const submitFormDebounceHandler = debounce(submitForm, 500);
  const submitFormevaluationDebounceHandler = debounce(submitFormevaluation, 500);

  function submitForm() {
    proxy.$refs["addevaluationItemRef"].validate((valid) => {
      if (valid) {
        let obj = {};

        for (let i in addevaluationItem.value.evaluationItemOptionList) {
          if (!addevaluationItem.value.evaluationItemOptionList[i].name) {
            proxy.$modal.msgError(`请输入第${i - 0 + 1}个选项`);
            return false;
          }
          if (
            isNumber(addevaluationItem.value.evaluationItemOptionList[i].score) ==
            false||addevaluationItem.value.evaluationItemOptionList[i].score<0
          ) {
            proxy.$modal.msgError(`请正确输入第${i - 0 + 1}个分值`);
            return false;
          }
          if(addevaluationItem.value.evaluationItemOptionList[i].name.length>100){
            proxy.$modal.msgError(`评估项目选项名称过长`);
            return false;
          }
          if (
            addevaluationItem.value.evaluationItemOptionList[i].score ===
              undefined ||
            addevaluationItem.value.evaluationItemOptionList[i].score === null ||
            addevaluationItem.value.evaluationItemOptionList[i].score === ""
          ) {
            proxy.$modal.msgError(`请输入第${i - 0 + 1}个分值`);
            return false;
          }
          if(addevaluationItem.value.evaluationItemOptionList[i].score.toString().length>8){
            proxy.$modal.msgError(`输入第${i - 0 + 1}个分值长度过长`);
            return false;
          }
        }
        obj = deepCopy(addevaluationItem.value);
        if (addEditFlag.value == "add") {
          form.value.evaluationItemList.push(obj);
        } else if (addEditFlag.value == "edit") {
          form.value.evaluationItemList.splice(editIndex.value, 1);
          form.value.evaluationItemList.splice(editIndex.value, 0, obj);
        }

        cancel();
      }
    });
  }

  function isNumber(value) {
    return typeof value === "number";
  }

  function hasDuplicateNames(arr) {
    let nameSet = new Set();

    for (let i = 0; i < arr.length; i++) {
      let template = arr[i];

      if (template.hasOwnProperty("name")) {
        let templateName = template.name;

        if (nameSet.has(templateName)) {
          return true; // 如果发现重复的名称，返回true
        } else {
          nameSet.add(templateName);
        }
      }
    }

    return false; // 如果没有发现重复的名称，返回false
  }
  function hasDuplicateResult(arr) {
    let nameSet = new Set();

    for (let i = 0; i < arr.length; i++) {
      let template = arr[i];

      if (template.hasOwnProperty("evaluationResult")) {
        let templateName = template.evaluationResult;

        if (nameSet.has(templateName)) {
          return true; // 如果发现重复的名称，返回true
        } else {
          nameSet.add(templateName);
        }
      }
    }

    return false; // 如果没有发现重复的名称，返回false
  }

  /**
   * 评分区间是否存在重叠
   * @param {*} evaluationCriteriaList 用户输入的评分标准项目
   * return isOverlap true | flase
   */
  function isOverlapByRange(evaluationCriteriaList) {
    let isOverlap = false

    if (evaluationCriteriaList != null && evaluationCriteriaList.length > 1) {
      evaluationCriteriaList.forEach(item => {
        evaluationCriteriaList.forEach(subItem => {
          if (item.beginScore !== subItem.beginScore || item.endScore !== subItem.endScore) {
            if (
              (subItem.beginScore <= item.beginScore && item.beginScore <= subItem.endScore) ||
              (subItem.beginScore <= item.endScore && item.endScore <= subItem.endScore)
            ) {
              isOverlap = true
              return
            }
          }
        })
      })
    }

    return isOverlap
  }

  function submitFormevaluation() {
    proxy.$refs["TemplateRef"].validate((valid) => {
      if (valid) {
        if(hasDuplicateResult(form.value.evaluationCriteriaList)){
          proxy.$modal.msgError(`评估标准中的评估结果不能重复`);
          return false;
        }
        if (hasDuplicateNames(form.value.evaluationItemList)) {
          proxy.$modal.msgError(`评估项目名字不能重复`);
          return false;
        }
        for (let i in form.value.evaluationCriteriaList) {
          if (
            isNumber(form.value.evaluationCriteriaList[i].beginScore) == false
          ) {
            proxy.$modal.msgError(`请正确输入第${i - 0 + 1}个开始分值`);
            return false;
          }
          if (isNumber(form.value.evaluationCriteriaList[i].endScore) == false) {
            proxy.$modal.msgError(`请正确输入第${i - 0 + 1}个结束分值`);
            return false;
          }
          if (
            form.value.evaluationCriteriaList[i].beginScore === undefined ||
            form.value.evaluationCriteriaList[i].beginScore === null ||
            form.value.evaluationCriteriaList[i].beginScore === ""
          ) {
            proxy.$modal.msgError(`请输入第${i - 0 + 1}个开始分值`);
            return false;
          }
          if (!form.value.evaluationCriteriaList[i].endScore) {
            proxy.$modal.msgError(`请输入第${i - 0 + 1}个结束分值`);
            return false;
          }
          if (!form.value.evaluationCriteriaList[i].evaluationResult) {
            proxy.$modal.msgError(`请输入第${i - 0 + 1}个评审结果`);
            return false;
          }
          if (form.value.evaluationCriteriaList[i].evaluationResult.length>100) {
            proxy.$modal.msgError(`第${i - 0 + 1}个评审结果过长`);
            return false;
          }
          if (
            form.value.evaluationCriteriaList[i].beginScore >=
            form.value.evaluationCriteriaList[i].endScore
          ) {
            proxy.$modal.msgError(`第${i - 0 + 1}个开始分值不能大于结束分值`);
            return false;
          }
        }

        let isOverlap = isOverlapByRange(form.value.evaluationCriteriaList)

        if(isOverlap) { // 如果评分区间存在重叠
          proxy.$modal.msgError("评分区间存在重叠")
          return false
        }

        if (form.value.id != undefined) {
          evaluationTemplateUpdate(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            router.go(-1);
          });
        } else {
          evaluationTemplateSave(form.value).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            router.go(-1);
          });
        }
      }
    });
  }

  //深拷贝
  function deepCopy(obj) {
    if (obj === null || typeof obj !== "object") {
      // 如果是基本数据类型或null，直接返回
      return obj;
    }

    if (Array.isArray(obj)) {
      // 如果是数组，遍历数组并递归地复制每个元素
      return obj.map(deepCopy);
    }

    // 如果是对象，遍历对象的属性并递归地复制每个属性值
    const copiedObj = {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        copiedObj[key] = deepCopy(obj[key]);
      }
    }

    return copiedObj;
  }

  function getevaluationTemplateInfo(id) {
    evaluationTemplateInfo(id).then((res) => {
      form.value = res.evaluationTemplate;
    });
  }

  const stopWatch = watch(
    () => route,
    (newVal, oldVal) => {
      if (newVal.params.id && newVal.params.id != "0") {
        getevaluationTemplateInfo(newVal.params.id);
      }
    },
    { immediate: true },
  );

  onBeforeUnmount(() => {
    stopWatch();
  });
</script>

<style scoped lang="scss">
  .addTemplate_container {
    padding: 20px;
  }
</style>
